import React, { useEffect, useState } from "react";
import XTable from "../XTable";
import './page.css'
import { Button, Form, Input, Radio, DatePicker, Space, Select } from 'antd';
import { getOrders, getCurrencies, getCustomers, getPayterms, getOrderDetails, getCustomerGoods } from "@/database";
import XSelect from "@/demos/XSelect";
import { customerSelectColumns, orderTableColumns, paytermSelectColumns, orderDetailColumns, customerGoodsSeletColumns } from "@/constants";

let isLoaded = false
import dayjs from 'dayjs';


const Detail = ({ order }) => {
    const [details, setDetails] = useState([]);
    const [currencies, setCurrencies] = useState([])
    const [customers, setCustomers] = useState([])
    const [payterms, setPayterms] = useState([])
    const [customerID, setCustomerID] = useState(0)
    const [customerName, setCustomerName] = useState('')
    const [customerGoods, setCustomerGoods] = useState([])
    const [detailColumns, setDetailCoumns] = useState(orderDetailColumns)
    useEffect(() => {
        console.log('render form...', order)

        if (order) {
            const newForm = {
                OrderSN: order.OrderSN,
                CustomerPO: order.CustomerPO,
                CurrencyID: order.CurrencyID,
                CustomerID: order.CustomerID,
                PayTermID: order.PayTermID,
            }
            newForm.CreateTime = dayjs(order.CreateTime)
            form.setFieldsValue(newForm);
            setCustomerID(newForm.CustomerID)
            getOrderDetails(order.OrderId).then(res => {
                onCustomerChange(order.CustomerID)
                setDetails(predata => res)
            })
        }
        if (!isLoaded) {

            getCurrencies().then(data => {
                setCurrencies(data)
            })

            getCustomers().then(res => {
                setCustomers(res)
            })

            getPayterms().then(res => {
                setPayterms(res)
            })

            isLoaded = true;
        }
    }, [order]);
    const [form] = Form.useForm();
    const [formLayout, setFormLayout] = useState('horizontal');

    const onFormLayoutChange = ({ layout }) => {
        setFormLayout(layout);
    };

    const formItemLayout =
        formLayout === 'horizontal' ? { labelCol: { span: 4 }, wrapperCol: { span: 14 } } : null;

    const buttonItemLayout =
        formLayout === 'horizontal' ? { wrapperCol: { span: 14, offset: 4 } } : null;
    const loadOrders = () => {

    }
    const onSelectChange = (row, colIdx) => {

    }

    const onCustomerChange = (customerID) => {
        getCustomerGoods(order.CustomerID).then(res => {
            console.log("客户特殊货号：", res)
            setDetailCoumns(predata => predata.map(d => {
                if (d.prop == 'GoodsNum') {
                    d.settings = {
                        dataSource: res,
                        columns: customerGoodsSeletColumns,
                        valueField: 'CustomerGoodsID',
                        displayField: 'Number',
                        onCommit: (rowIdx, column, val) => {
                            console.log('on customer goods commit:', rowIdx, column, val)
                        }
                    }
                }
                return d
            }))
        })
    }

    const onCellEditCommit = (row, column, rowIdx, colIdx) => {
        console.log(rowIdx, colIdx)
    }

    const getOrderTableColumns = (cus) => {
        const cs = orderTableColumns.map(item => {
            if (item.prop == 'CustomerCode') {
                item.settings = {
                    columns: customerSelectColumns,
                    dataSource: cus,
                    valueField: "CustomerID",
                    displayField: "CustomerCode"
                }
                item.onCommit = (rowIdx, column, val) => {
                    setOrders(predata => {
                        predata[rowIdx]['CustomerName'] = val.selRow['CustomerName']
                        return predata
                    })
                }
            }
            return item
        })
        return cs;
    }

    return (
        <div>
            <Form
                layout={`inline`}
                form={form}
                initialValues={{ layout: formLayout }}
                onValuesChange={onFormLayoutChange}
            >
                <Form.Item label="订单编号" name="OrderSN">
                    <Input placeholder="订单编号" readOnly={true} size="small" />
                </Form.Item>
                <Form.Item label="订单日期" name="CreateTime">
                    <DatePicker placeholder="选择日期" size="small" />
                </Form.Item>
                <Form.Item label="客户PO" name="CustomerPO">
                    <Input placeholder="客户PO" size="small" />
                </Form.Item>
                <Form.Item label="货币" name="CurrencyID">
                    <Select placeholder="选择货币" size="small" onChange={e => {
                        form.setFieldValue('CurrencyID', e.currentTarget.value)
                    }}>
                        {currencies.map((cur, idx) => {
                            return (
                                <Select.Option key={idx} value={cur.CurrencyID}>{cur.CurrencyName}</Select.Option>
                            )
                        })}
                    </Select>
                </Form.Item>
                <Form.Item label="客户编码">
                    <div className="flex">
                        <XSelect columns={customerSelectColumns} dataSource={customers}
                            valueField="CustomerID"
                            onChange={opt => {
                                console.log('customer changed..')
                                form.setFieldValue('CustomerID', opt.CustomerID)
                                console.log(opt)
                                setCustomerName(opt.CustomerName)
                                onCustomerChange(opt.CustomerID)
                            }}
                            value={customerID}
                            displayField={`CustomerCode`} />
                        <Input placeholder="客户名称" readOnly={true} size="small" value={customerName} />
                    </div>
                </Form.Item>
                <Form.Item label="付款期" name="PaytermID">
                    <XSelect columns={paytermSelectColumns} dataSource={payterms} valueField="PayTermID"
                        onChange={opt => {
                            form.setFieldValue('PayTermID', opt.PayTermID)
                        }}
                        displayField="PayTermName" />
                </Form.Item>
            </Form>
            <XTable columns={detailColumns} data={details} selectMode="column" selectable={true}
                onSelectChange={onSelectChange} editable={true}
                onCommit={onCellEditCommit} />
        </div>
    )
}

export default Detail